<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="源头业务对象" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fromobjectcode">
              <j-search-select-tag v-model="model.fromobjectcode" dict="scmobject,objectname,objectcode" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="源头主表" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="frommaintable">
              <j-search-select-tag
                v-model="model.frommaintable"
                dict="onl_cgform_head where table_type ='1',table_txt,id"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="源头分表" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fromitemtable">
              <j-search-select-tag
                v-model="model.fromitemtable"
                dict="onl_cgform_head where table_type ='1',table_txt,id"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="源头关联字段" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fromlinkid">
              <a-input v-model="model.fromlinkid" placeholder="请输入源头关联字段"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="去向业务对象" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="endobjectcode">
              <j-search-select-tag v-model="model.endobjectcode" dict="scmobject,objectname,objectcode" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="去向主表" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="endmaintable">
              <j-search-select-tag
                v-model="model.endmaintable"
                dict="onl_cgform_head where table_type ='1',table_txt,id"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="去向分表" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="enditemtable">
              <j-search-select-tag
                v-model="model.enditemtable"
                dict="onl_cgform_head where table_type ='1',table_txt,id"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="去向关联字段" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="endlinkid">
              <a-input v-model="model.endlinkid" placeholder="请输入去向关联字段"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="数据转换规则分录主表" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="dataconvertruleitemmainTable.loading"
          :columns="dataconvertruleitemmainTable.columns"
          :dataSource="dataconvertruleitemmainTable.dataSource"
          :maxHeight="500"
          :disabled="formDisabled"
          :alwaysEdit="true"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true">
          <template slot="toolbarSuffix">
              <a-button type="primary" @click="getReferCol">加载列表信息</a-button>
            </template>
        </j-vxe-table>
      </a-tab-pane>
      <a-tab-pane tab="数据转换规则分录分表" :key="refKeys[1]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[1]"
          :loading="dataconvertruleitemitemTable.loading"
          :columns="dataconvertruleitemitemTable.columns"
          :dataSource="dataconvertruleitemitemTable.dataSource"
          :maxHeight="500"
          :alwaysEdit="true"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true">
          <template slot="toolbarSuffix">
              <a-button type="primary" @click="getReferItemCol">加载列表信息</a-button>
            </template>
        </j-vxe-table>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>
import { getAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'

export default {
  name: 'DataconvertruleForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      model: {},
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {},
      mainFrom:'onl_cgform_field,db_field_txt,db_field_name',
      itemFrom:'onl_cgform_field,db_field_txt,db_field_name',
      refKeys: ['dataconvertruleitemmain', 'dataconvertruleitemitem'],
      tableKeys: ['dataconvertruleitemmain', 'dataconvertruleitemitem'],
      activeKey: 'dataconvertruleitemmain',
      // 数据转换规则分录主表
      dataconvertruleitemmainTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '去向列',
            key: 'tocolcode',
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '去向列名称',
            key: 'tocolname',
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '转换规则',
            key: 'converttype',
            type: JVXETypes.sel_search,
            dictCode: 'converttype',
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: 'zdys'
          },
          {
            title: '源头列',
            key: 'fromcolcode',
            type: JVXETypes.sel_search,
            dictCode: this.mainFrom,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '源头列名称',
            key: 'fromcolname',
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          }
        ]
      },
      // 数据转换规则分录分表
      dataconvertruleitemitemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '去向列',
            key: 'tocolcode',
            type: JVXETypes.sel_search,
            dictCode: '',
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '去向列名',
            key: 'tocolname',
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '转换规则',
            key: 'converttype',
            type: JVXETypes.sel_search,
            dictCode: 'converttype',
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: 'zdys'
          },
          {
            title: '源头列',
            key: 'fromcolcode',
            type: JVXETypes.sel_search,
            dictCode: this.itemFrom,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '源头列名',
            key: 'fromcolname',
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          }
        ]
      },
      url: {
        add: '/sysplatform/dataconvertrule/add',
        edit: '/sysplatform/dataconvertrule/edit',
        queryById: '/sysplatform/dataconvertrule/queryById',
        dataconvertruleitemmain: {
          list: '/sysplatform/dataconvertrule/queryDataconvertruleitemmainByMainId',
          getmainformfield:'/base/erponlineform/getcgformfieldbyheadid',
        },
        dataconvertruleitemitem: {
          list: '/sysplatform/dataconvertrule/queryDataconvertruleitemitemByMainId',
          getitemformfield:'/base/erponlineform/getcgformfieldbyheadid',
        }
      }
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  watch:{
    /**
     * 如果主表发生变化，则将分录的下的帮助重置一下
     */
    'model.frommaintable':{
      handler(val,oldvalue){
        if(val){
         // this.mainFrom = "onl_cgform_field where cgform_head_id ='"+ val + "',db_field_txt,db_field_name";
         for (let i = 0; i < this.dataconvertruleitemmainTable.columns.length; i++) {
            if (this.dataconvertruleitemmainTable.columns[i].key === 'fromcolcode') {
              let curcolumn = this.dataconvertruleitemmainTable.columns[i]
              delete curcolumn.dictCode
              this.$set(curcolumn, 'dictCode', "onl_cgform_field where cgform_head_id ='"+ val + "',db_field_txt,db_field_name")
              break
            }
          }
        }
      }
    },
    'model.fromitemtable':{
      handler(val,oldvalue){
        if(val){
          this.itemFrom = "onl_cgform_field where cgform_head_id ='"+ val + "',db_field_txt,db_field_name";
          for (let i = 0; i < this.dataconvertruleitemitemTable.columns.length; i++) {
            if (this.dataconvertruleitemitemTable.columns[i].key === 'fromcolcode') {
              let curcolumn = this.dataconvertruleitemitemTable.columns[i]
              delete curcolumn.dictCode
              this.$set(curcolumn, 'dictCode',"onl_cgform_field where cgform_head_id ='"+ val + "',db_field_txt,db_field_name")
              break
            }
          }
        }
      }
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    }
  },
  created() {},
  methods: {
    /**
     * 加载分录列表信息
     */
    getReferItemCol(){
      let itemtable = this.model.enditemtable;
      if(itemtable){
        getAction(this.url.dataconvertruleitemitem.getitemformfield,{headid:itemtable}).then(res=>{
          if(res){
            if(res.success){
              let resu  = res.result;
              this.dataconvertruleitemitemTable.dataSource=[];
              let newDataSource=[];
              for(let i=0;i<resu.length;i++){
                let newRow={
                  tocolcode:resu[i].dbfieldname,
                  tocolname:resu[i].dbfieldtxt,
                  converttype:'zdys',
                }
                newDataSource.push(newRow);
              }
              this.dataconvertruleitemitemTable.dataSource = newDataSource;
            }
          }
        })
      }
    },
    /**
     * 加载主分录列表信息
     */
    getReferCol(){
      let maintable = this.model.endmaintable;
      if(maintable){
        getAction(this.url.dataconvertruleitemmain.getmainformfield,{headid:maintable}).then(res=>{
          if(res){
            if(res.success){
              let resu  = res.result;
              this.dataconvertruleitemmainTable.dataSource=[];
              let newDataSource=[];
              for(let i=0;i<resu.length;i++){
                let newRow={
                  tocolcode:resu[i].dbfieldname,
                  tocolname:resu[i].dbfieldtxt,
                  converttype:'zdys',
                }
                newDataSource.push(newRow);
              }
              this.dataconvertruleitemmainTable.dataSource = newDataSource;
            }
          }
        })
      }
    },
    addBefore() {
      this.dataconvertruleitemmainTable.dataSource = []
      this.dataconvertruleitemitemTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {})
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.dataconvertruleitemmain.list, params, this.dataconvertruleitemmainTable)
        this.requestSubTableData(this.url.dataconvertruleitemitem.list, params, this.dataconvertruleitemitemTable)
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch(e => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        dataconvertruleitemmainList: allValues.tablesValue[0].tableData,
        dataconvertruleitemitemList: allValues.tablesValue[1].tableData
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    }
  }
}
</script>

<style scoped></style>
